package com.gin.kotlin.no_gay_alliance.listener

import android.content.Context
import android.content.DialogInterface
import android.widget.FrameLayout
import android.widget.ImageView
import com.gin.kotlin.no_gay_alliance.app.App
import com.gin.kotlin.no_gay_alliance.app.App.Companion.DOWNLOAD_DIR
import com.gin.kotlin.no_gay_alliance.base.AlertDialogUtils
import com.gin.kotlin.no_gay_alliance.base.ClipboardUtils
import com.gin.kotlin.no_gay_alliance.base.DownloadUtils
import com.wgw.photo.preview.interfaces.OnLongClickListener
import okhttp3.HttpUrl.Companion.toHttpUrl

/**
 * 预览图的长按响应
 * @constructor
 */
class PhotoPreviewLongClickListener(val context: Context, private val obtainImage: (position: Int) -> PreviewImage) : OnLongClickListener {

    override fun onLongClick(position: Int, customViewRoot: FrameLayout?, imageView: ImageView?): Boolean {
        val previewImage = obtainImage.invoke(position)

        val filename = previewImage.url.toHttpUrl().pathSegments.last()

        val listener: (dialog: DialogInterface, which: Int) -> Unit = { _, which ->
            when (which) {
                // 下载原图
                DialogInterface.BUTTON_POSITIVE -> {
                    App.INSTANCE.handler?.toast("开始下载")
                    DownloadUtils.enqueue(context, listOf(DownloadUtils.DownloadOption(previewImage.url, "$DOWNLOAD_DIR/$filename")))
                }
                // 复制代码
                DialogInterface.BUTTON_NEGATIVE -> ClipboardUtils.setText(previewImage.code, context)
                // 复制链接
                DialogInterface.BUTTON_NEUTRAL -> ClipboardUtils.setText(previewImage.url, context)
            }
        }
        AlertDialogUtils.builder(context, title = "请选择你想要的操作", message = "点击弹窗外取消")
            .setPositiveButton("下载原图", listener)
            .setNeutralButton("复制链接", listener)
            .also { if (previewImage.code.isNotEmpty()) it.setNegativeButton("复制代码", listener) }
            .show()

        return true
    }

    data class PreviewImage(
        val url: String,
        val code: String,
    )
}